package com.yps.io.aio.client;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;

public class WriteHandler implements CompletionHandler<Integer, ByteBuffer>{
	private AsynchronousSocketChannel channel;
	private CountDownLatch latch;
	public WriteHandler(AsynchronousSocketChannel channel) {
		this.channel = channel;
	}
	public WriteHandler(AsynchronousSocketChannel clientChannel,CountDownLatch latch) {  
	    this.channel = clientChannel;  
	    this.latch = latch;  
	}  
	@Override
	public void completed(Integer result, ByteBuffer attachment) {
		//如果没有发送完，继续发送知道完成
		if (attachment.hasRemaining()){
			channel.write(attachment, attachment, this);
		}else {
			//创建新的Buffer
			ByteBuffer readBuffer = ByteBuffer.allocate(1024);
			//异步读， 但三个成为接收消息回调的业务的handle
			if(latch == null)
				channel.read(readBuffer, readBuffer, new ReadHandler(channel));
			else
				channel.read(readBuffer, readBuffer, new ReadHandler(channel, latch));
		}
	}

	
	@Override
	public void failed(Throwable exc, ByteBuffer attachment) {
		try {
			this.channel.close();
			if (latch != null){
				latch.countDown();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("数据发送是失败...");
	}

}
